package com.itsitio.registeradmin.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.itsitio.registeradmin.dto.CompanyDTO;
import com.itsitio.registeradmin.model.Company;
import com.itsitio.registeradmin.model.CompanyFirmName;
import com.itsitio.registeradmin.model.CompanyType;
import com.itsitio.registeradmin.model.UserRegistration;
import com.itsitio.registeradmin.service.CompanyFirmSrv;
import com.itsitio.registeradmin.service.CompanySrv;
import com.itsitio.registeradmin.service.CompanyTypeSrv;
import com.itsitio.registeradmin.service.UserRegistrationSrv;
import com.itsitio.registeradmin.web.UserContext;

@Controller
@SessionAttributes({"userContext"})
public class CompanyController extends BaseController{
	
	@Autowired
	private UserRegistrationSrv userRegSrv;
	
	@Autowired
	private CompanySrv companySrv;
	
	@Autowired
	private CompanyFirmSrv companyFirmSrv;
	
	@Autowired
	private CompanyTypeSrv companyTypeSrv;

	/**
	 * Muestra la pantalla de Empresa: 
	 * - formulario cargado con los datos de la empresa que cargo el usuario al registrarse
	 * - lista de empresas que tienen razon social parecida 
	 * a la que cargo el usuario y/o cuil = al cargado por el usuario. 
	 * @param model
	 * @param userRegId
	 * @return
	 */
	@RequestMapping("/showCompanySection.html")
	public String showCompanySection(Model model, @RequestParam(value="userRegId") Integer userRegId, HttpServletRequest request, @ModelAttribute UserContext userContext) {
		
		List<CompanyDTO> companyList = null;
		
		UserRegistration userRegistration = userRegSrv.get(userRegId);
		
		//filtra la lista de empresas por similar razon social y cuit 
		companyList = companySrv.getCompanyDtoListByCriteria(userRegistration.getCompanyTaxId(), userRegistration.getCompanyFirmName());
		
		model.addAttribute("newCompany", getNewCompany(userRegistration));
		model.addAttribute("companyList", companyList);
		model.addAttribute("userRegId", userRegId);
		model.addAttribute("companyTypes", getCompanytypes());
		
		// bread crumbs
		userContext.setUserRegFirstname(userRegistration.getUserFirstName());
		userContext.setUserRegLastname(userRegistration.getUserLastName());
		userContext.setUserRegMail(userRegistration.getUserEmail());
		userContext.setUserRegMail(userRegistration.getUserEmail());
		userContext.setUserCity(userRegistration.getUserCity());
		userContext.setUserPhone(userRegistration.getUserPhone());
		
		return forward("company/companySection", model);
	}
	
	/**
	 * @return
	 */
	private List<CompanyType> getCompanytypes() {
		return companyTypeSrv.obtenerTodos();
	}

	public CompanyDTO getNewCompany(UserRegistration userRegistration) {
		CompanyDTO companyDTO = new CompanyDTO();
		
		//carga el formulario de nueva empresa
		if(userRegistration != null){

			companyDTO.setFirmName(userRegistration.getCompanyFirmName());
			companyDTO.setTaxId(userRegistration.getCompanyTaxId());
			if(userRegistration.getCompanyType()!= null){
				companyDTO.setType(userRegistration.getCompanyType().getName());
				companyDTO.setIdType(userRegistration.getCompanyType().getId());
			}
			companyDTO.setTradeName(userRegistration.getCompanyTradeName());
			companyDTO.setWebsite(userRegistration.getCompanyWebsite());
			
			
		} 
		return companyDTO;
	} 
	
	@RequestMapping("/searchCompany.html")
	public String searchCompany(Model model, @RequestParam(required=false) Integer userRegId, 
			@RequestParam(required=false) Integer opcionBusqueda,
			@RequestParam(required=false) String campoBusqueda) {
		List<CompanyDTO> companyList = null;
		UserRegistration userRegistration = null;
		String taxIdSearch = "";
		String firmNameSearch = "";
		
		if(userRegId != null && !userRegId.equals("")){
			userRegistration = userRegSrv.get(userRegId);
			taxIdSearch = userRegistration.getCompanyTaxId();
			firmNameSearch = userRegistration.getCompanyFirmName();
		}
		
		if(opcionBusqueda != null && opcionBusqueda.equals(1)){
			taxIdSearch = campoBusqueda;
			firmNameSearch = "";
		}
		
		if(opcionBusqueda != null && opcionBusqueda.equals(2)){
			taxIdSearch = "";
			firmNameSearch = campoBusqueda;
		}
		
		companyList = companySrv.getCompanyDtoListByCriteria(taxIdSearch, firmNameSearch);
		
		model.addAttribute("companyList", companyList);
		model.addAttribute("userRegId", userRegId);
		model.addAttribute("opcionBusqueda", opcionBusqueda);
		model.addAttribute("campoBusqueda", campoBusqueda);
		model.addAttribute("newCompany", getNewCompany(userRegistration));
		model.addAttribute("companyTypes", getCompanytypes());
		return forward("company/companySection", model);     
	} 
	

	/**
	 * @param model
	 * @param action
	 * @return
	 */
	@RequestMapping("/updateCompany.html")
	public String updateCompany(Model model, @RequestParam String nextStep,
			@RequestParam Integer userRegId, @RequestParam Integer selectedCompany,
			@RequestParam String firmName, @RequestParam String tradeName, 
			@RequestParam Integer type2,@RequestParam String website, @RequestParam String taxid) {
		
		Company newCompany = null;
		CompanyFirmName companyFirmName = null;
		Integer companyId =  selectedCompany;
		
		if(nextStep.equalsIgnoreCase("actualizar")){
			
			companySrv.updateCompanyWithUserRegistrationData(selectedCompany,
					firmName, tradeName, type2,website, taxid);
			
		} else if (nextStep.equalsIgnoreCase("nuevaEmpresa")){
			
			newCompany = companySrv.createCompanyFromUserRegistration(firmName, tradeName, type2,website, taxid);
			companyId =  newCompany.getId();
			
		}else if (nextStep.equalsIgnoreCase("nuevaRazon")){
			
			companyFirmName = companyFirmSrv.createCompanyFirmFromUserRegistration(selectedCompany,firmName,taxid);
			
		} 
		
		return "redirect:/showBranchSection.html?userRegId=" + userRegId + "&companyId="+companyId;
	}
	
	
	/**
	 * @param id
	 * @return la vista con el detalle de Empresa
	 */
	@RequestMapping("/showCompanyDetail.html")
	public  String showCompanyDetail(@RequestParam  Integer companyId, Model model) 
	{
		Company company = companySrv.getCompanyById(companyId);
		

		model.addAttribute("razones", company.getCompanyFirmNames());
		return "company/companyDetail";   
	}
	

}
